<template>
    <a-modal
        v-model:visible="visible"
        :title="title"
        :on-before-ok="handleBeforeOk"
        @cancel="handleCancel"
    >
        <template #title></template>
        <div>
            <a-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                auto-label-width
            >
                <a-form-item field="oldPassword" :label="$t('oldPass')">
                    <a-input-password v-model="formData.oldPassword" />
                </a-form-item>
                <a-form-item field="newPassword" :label="$t('newPass')">
                    <a-input-password v-model="formData.newPassword" />
                </a-form-item>
            </a-form>
        </div>
    </a-modal>
</template>

<script lang="ts" setup>
    import { ref, reactive, PropType, computed } from 'vue';
    import { useI18n } from 'vue-i18n';
    import { modPass } from './service';

    const { t } = useI18n();

    const emit = defineEmits(['submit']);

    const visible = ref(false);
    const formRef = ref();
    const title = t('modPass');
    const formData = reactive({
        oldPassword: '',
        newPassword: '',
    });
    const formRules = {
        oldPassword: [
            {
                required: true,
                message: t('input.placeholder') + t('oldPass'),
            },
        ],
        newPassword: [
            {
                required: true,
                message: t('input.placeholder') + t('newPass'),
            },
        ],
    };

    function open() {
        visible.value = true;
    }

    const handleBeforeOk = async () => {
        const res = await formRef.value.validate();
        const payload = {
            ...formData,
        };
        if (!res) {
            await modPass(payload);
            emit('submit');
            formRef.value.resetFields();
            return true;
        }
        return false;
    };

    function handleCancel() {
        formRef.value.resetFields();
        visible.value = false;
    }

    defineExpose({
        open,
    });
</script>
